package sg.edu.nus.iss.vmcs.store;

import java.io.IOException;

/*
 * @editedby A0119952X - Singleton Design Pattern
 */
public class CashStoreController extends StoreController {
    private static CashStoreController instance;
    private CashStoreController() {
        super();
    }

    public static CashStoreController getInstance() {
        if (instance == null) {
            instance = new CashStoreController();
        }
        return instance;
    }

	@Override
	protected Store createStore() {
		return new CashStore();
	}

	@Override
	protected void initializeItem(Store store, StoreItem item) {		
	}
	
	/**
	 * This method will instruct the {@link CashStore} to store the {@link Coin} sent as input, and
	 * update the display on the Machinery Simulator Panel.
	 * @param c the Coin to be stored.
	 */
	public void storeCoin(Coin c) {
		CashStoreItem item = getCashStore().findCashStore(c);
		item.increment();
	}
	
	/**
	 * This method will instruct the {@link CashStore} to store the {@link Coin} sent as input, and then
	 * update the display on the {@link sg.edu.nus.iss.vmcs.machinery.MachinerySimulatorPanel}.
	 * @return the number of cash transfered.
	 */
	public int transferAll()  {
		int i;
		int cc = 0; // coin quauntity;
		int size = store.getStoreSize();

		CashStoreItem item;
		for (i = 0; i < size; i++) {
			item = (CashStoreItem) store.getStoreItem(i);
			cc = cc + item.getQuantity();
			item.setQuantity(0);			
		}
		
		return cc;
	}
	
	/**
	 * This method returns the total number of cash held in the {@link CashStore}.
	 * @return the total number of cash held.
	 */
	public int getTotalCash(){
		return getCashStore().getTotalCash();
	}
	
	/**
	 * This method instructs the {@link CashStore} to issue a number of {@link Coin} of a specific
	 * denomination, and then updates the {@link sg.edu.nus.iss.vmcs.machinery.MachinerySimulatorPanel}&#46; It return TRUE
	 * or FALSE to indicate whether the change issue was successful&#46;
	 * @param idx the index of the Coin&#46;
	 * @param numOfCoins the number of Coin to deduct&#46; 
	 */
	public void giveChange(int idx, int numOfCoins)  {
		CashStoreItem item;
		item = (CashStoreItem) getStoreItem(idx);
		for (int i = 0; i < numOfCoins; i++)
			item.decrement();
	}
	
	private CashStore getCashStore() {
		return (CashStore)store;
	}
}
